package com.jing.ads.view;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.TouchDelegate;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jing.ads.R;
import com.jing.ads.downloader.DownloadManager;
import com.jing.ads.handler.LogHandler;
import com.jing.ads.model.Entry;
import com.jing.ads.model.PushAppInfo;
import com.jing.ads.model.PushAppInfo.AppDetail;
import com.jing.ads.net.ADSImgDownloader;
import com.jing.ads.net.RequestListener;
import com.jing.ads.net.ADSImgDownloader.ImgCallBack;
import com.jing.ads.services.BackgroudService;
import com.jing.ads.util.GlobalUtil;
import com.jing.ads.util.PreferenceUtil;

public class MainView extends LinearLayout {

	private static final String PUSH_SETTING = "push_setting";

	private Context context;

	private View contentLayout, settingLayout, settingBtn, pullBtn;

	private boolean noMore = false;

	private ArrayList<View> appList = new ArrayList<View>();

	private HashMap<AppDetail, View> appMap = new HashMap<AppDetail, View>();

	private LinearLayout oLayout, tLayout;
	private RadioButton fy, fn;

	private DownloadManager dm;
	private ADSImgDownloader downloader;

	private PushAppInfo info;
	private View newLayout, apk;
			
	private Handler handler;

	public MainView(Context context) {
		super(context);
		this.context = context;
		handler = new Handler();
		init();
	}

	private void init() {
		dm = DownloadManager.getInstance(context);
		downloader = ADSImgDownloader.getInstance(context);
		View view = LayoutInflater.from(context).inflate(R.layout.index_layout,
				null);
		contentLayout = view.findViewById(R.id.content);
		settingLayout = view.findViewById(R.id.setting);
		settingBtn = view.findViewById(R.id.setting_btn);
		pullBtn = view.findViewById(R.id.pull_btn);
		oLayout = (LinearLayout) view.findViewById(R.id.o_layout);
		tLayout = (LinearLayout) view.findViewById(R.id.t_layout);
		int oS = oLayout.getChildCount();
		for (int i = 0; i < oS; i++) {
			appList.add(oLayout.getChildAt(i));
		}
		int tS = tLayout.getChildCount();
		for (int i = 0; i < tS; i++) {
			appList.add(tLayout.getChildAt(i));
		}
		fy = (RadioButton) view.findViewById(R.id.frame_y);
		fn = (RadioButton) view.findViewById(R.id.frame_n);
		newLayout = view.findViewById(R.id.new_layout);
		apk = view.findViewById(R.id.new_apk);
		
		final String url = PreferenceUtil.getSharedString(context, "self_apk", "");
		if (!TextUtils.isEmpty(url)) {
			
			newLayout.setVisibility(View.VISIBLE);
			
			apk.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					initSelfUpdate(url);
				}
			});
		}else {
			newLayout.setVisibility(View.GONE);
		}
		this.setGravity(Gravity.CENTER_HORIZONTAL);
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		int h = wm.getDefaultDisplay().getHeight();
		this.setPadding(0, h / 4, 0, 0);
		this.addView(view);
		initSettingBtn();
		initSettingLayout();
		initPull();
		
	}

	private boolean checkSelfAPK(File file) {
		int code = PreferenceUtil.getSharedInt(context, "self_apk_code", 0);
		int ccode = GlobalUtil.getClientVersionCode(context);
		if (ccode >= code) {
			return false;
		}
		if (file != null && file.exists()) {
			long size = PreferenceUtil.getSharedLong(context, "self_apk_size", 0);
			long csize = file.length();
			if (size == csize) {
				return true;
			}
		}
		return false;
	}
	
	private void initSelfUpdate(String url) {
		File file = GlobalUtil.isDownloadAPk(context, url);
		if (file != null && file.exists()) {
			if (checkSelfAPK(file)) {
				GlobalUtil.startInstall(context, file);
			}else {
				file.delete();
				Toast.makeText(context, R.string.self_download, Toast.LENGTH_LONG).show();
				GlobalUtil.downloadSelf(context, url);
			}
		}else {
			Toast.makeText(context, R.string.self_download, Toast.LENGTH_LONG).show();
			GlobalUtil.downloadSelf(context, url);
		}
	}
	
	private void initPull() {
		tLayout.setVisibility(View.GONE);
		pullBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!noMore) {
					tLayout.setVisibility(tLayout.getVisibility() != View.VISIBLE ? View.VISIBLE
							: View.GONE);
				}
			}
		});
	}

	private void initSettingBtn() {
		settingBtn.post(new Runnable() {
			
			@Override
			public void run() {
				Rect r = new Rect();
				settingBtn.getHitRect(r);
				r.left -= 25;
				r.right += 25;
				r.top -= 50;
				r.bottom += 50;
				((View) settingBtn.getParent()).setTouchDelegate(new TouchDelegate(r, settingBtn));
			}
		});
		settingBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showContent(settingLayout.getVisibility() == View.VISIBLE);
			}
		});
	}

	private void showContent(boolean show) {
		settingLayout.setVisibility(show ? View.GONE : View.VISIBLE);
		contentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
		if (!show) {
			showOption();
			final String url = PreferenceUtil.getSharedString(context, "self_apk", "");
			if (!TextUtils.isEmpty(url)) {
				
				newLayout.setVisibility(View.VISIBLE);
				
				apk.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						initSelfUpdate(url);
					}
				});
			}else {
				newLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showOption() {
		String ps = PreferenceUtil.getSharedString(context, PUSH_SETTING, "y");
		if (ps.equals("y")) {
			fy.setChecked(true);
			fn.setChecked(false);
		} else {
			fy.setChecked(false);
			fn.setChecked(true);
		}
	}

	private void showYes(boolean show) {
		fy.setChecked(show);
		fn.setChecked(!show);
		Intent i = new Intent(show ? BackgroudService.ACTION_WINDOW_ADD
				: BackgroudService.ACTION_WINDOW_REMOVE);
		context.sendBroadcast(i);
	}

	private void initSettingLayout() {
		showOption();
		fy.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				PreferenceUtil.putSharedString(context, PUSH_SETTING, "y");
				showYes(true);
				showContent(true);
			}
		});
		fn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				PreferenceUtil.putSharedString(context, PUSH_SETTING, "n");
				showYes(false);
				showContent(true);
			}
		});
	}

	private void setAppView(final View view, final AppDetail app) {
		appMap.put(app, view);
		final View mask = view.findViewById(R.id.progress_layout);
		final ProgressBar pb = (ProgressBar) view
				.findViewById(R.id.app_progress);
		TextView name = (TextView) view.findViewById(R.id.app_name);
		String t = "";
		final int s = app.downloadStatus;
		if (s == AppDetail.DOWNLOADING) {
			View v = view.findViewById(R.id.progress_layout);
			v.setVisibility(View.VISIBLE);
			pb.setMax(app.size);
			pb.setProgress(app.downloadCount);
			t = context.getString(R.string.downloading);
		} else if (s == AppDetail.DOWNLOADED) {
			mask.setVisibility(View.GONE);
			if (GlobalUtil.isInstalledApp(context, app.packageName)) {
				t = context.getString(R.string.launch_app);
			} else {
				t = context.getString(R.string.install_app);
			}
		} else if (s == AppDetail.UNDOWNLOAD) {
			t = app.appName;
		} else if (s == AppDetail.PAUSE) {
			View v = view.findViewById(R.id.progress_layout);
			v.setVisibility(View.VISIBLE);
			pb.setMax(app.size);
			pb.setProgress(app.downloadCount);
			t = context.getString(R.string.downloading);
		}
		name.setText(t);
		final ImageView icon = (ImageView) view.findViewById(R.id.app_icon);
		icon.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int ss = app.downloadStatus;
				if (ss == AppDetail.DOWNLOADED) {
					mask.setVisibility(View.GONE);
					if (GlobalUtil.isInstalledApp(context, app.packageName)) {
						LogHandler lh = new LogHandler(context);
				    	lh.setParams(LogHandler.ACTION_ACTIVE, app.packageName);
				    	lh.onRequest(new RequestListener() {
							
							@Override
							public void onError(Object error) {
								
							}
							
							@Override
							public void onCallBack(Object data) {
								
							}
						}, false);
						Intent i = GlobalUtil.getAppLaunchIntent(
								context.getPackageManager(), app.packageName);
						i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(i);
					} else {
						LogHandler lh = new LogHandler(context);
				    	lh.setParams(LogHandler.ACTION_INSTALL, app.packageName);
				    	lh.onRequest(new RequestListener() {
							
							@Override
							public void onError(Object error) {
								
							}
							
							@Override
							public void onCallBack(Object data) {
								
							}
						}, false);
						GlobalUtil
								.startInstall(context, new File(app.filePath));
					}
				} else if (ss == AppDetail.UNDOWNLOAD) {
					dm.startDownload(app.downloadUrl,
							Integer.valueOf(app.appId), app.packageName, app.appName,
							app.size);
					app.downloadStatus = AppDetail.DOWNLOADING;
					mask.setVisibility(View.VISIBLE);
					pb.setProgress(0);
					pb.setMax(100);
				} else if (ss == AppDetail.DOWNLOADING) {
					return;
				} else if (ss == AppDetail.PAUSE) {
					dm.startDownload(app.downloadUrl,
							Integer.valueOf(app.appId), app.packageName, app.appName,
							app.size);
				}
			}
		});
		downloader.onDownload(app.iconUrl, new ImgCallBack() {

			@Override
			public void callback(final Bitmap bitmap) {
				if (bitmap == null) {
					return;
				}
				handler.post(new Runnable() {

					@Override
					public void run() {
						icon.setImageDrawable(new BitmapDrawable(bitmap));
					}
				});
			}
		});
	}

	private void setData(PushAppInfo info) {
		int size = info.getAppsList().size();
		int offset = size > 10 ? 10 : size;
		for (int i = 0; i < offset; i++) {
			setAppView(appList.get(i), info.getAppsList().get(i));
		}
		for (int i = offset; i < 10; i++) {
			appList.get(i).setVisibility(View.INVISIBLE);
		}
		noMore = size <= 5;

	}

	public void setData(Entry entry) {
		if (entry instanceof PushAppInfo) {
			appMap.clear();
			info = (PushAppInfo) entry;
			setData(info);
		}
	}

	public void setProgress(final String pName, final int progress,
			final int total) {
		for (final AppDetail app : appMap.keySet()) {
			if (app.packageName.equals(pName)) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						View view = appMap.get(app);
						ProgressBar pb = (ProgressBar) view
								.findViewById(R.id.app_progress);
						pb.setMax(total);
						pb.setProgress(progress);
						app.downloadStatus = AppDetail.DOWNLOADING;
						TextView n = (TextView) view
								.findViewById(R.id.app_name);
						n.setText(R.string.downloading);
						app.size = total;
						app.downloadCount = progress;
					}
				});
				break;
			}
		}
	}

	public void setComplete(String pName, final String path) {
		for (final AppDetail app : appMap.keySet()) {
			if (app.packageName.equals(pName)) {
				app.filePath = path;
				handler.post(new Runnable() {

					@Override
					public void run() {
						View view = appMap.get(app);
						app.downloadStatus = AppDetail.DOWNLOADED;
						TextView n = (TextView) view
								.findViewById(R.id.app_name);
						n.setText(R.string.install_app);
						View m = view.findViewById(R.id.progress_layout);
						m.setVisibility(View.GONE);
						GlobalUtil.startInstall(context, new File(path));
					}
				});
				break;
			}
		}
	}

	public void setError(String pName) {

	}
}
